package com.lagou.rpc.provider.server;

import com.lagou.rpc.provider.handler.RpcServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * RPC服务端
 */
@Component
public class RpcServer implements DisposableBean {

    /**
     * 声明线程池
     */
    private EventLoopGroup boosLoopGroup = new NioEventLoopGroup(1);
    private EventLoopGroup workerLoopGroup = new NioEventLoopGroup();

    /**
     * Zookeeper客户端
     */
    private ZkClient zkClient = new ZkClient("0.0.0.0:2181");

    @Autowired
    private RpcServerHandler rpcServerHandler;

    /**
     * 启动Rpc服务器
     */
    public void runServer(String ip,int port){
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosLoopGroup,workerLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,120)
                    .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS,2000)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(rpcServerHandler);
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(ip, port).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()) {
                        // 当服务器启动成功，发送注册信息到zk
                        // 创建持久节点，保存服务器信息
                        String serverNodePath = "/server/" + ip +":" + port;
                        if(!zkClient.exists(serverNodePath)){
                            zkClient.createPersistent(serverNodePath,!zkClient.exists("/server"));
                        }
                        // 创建临时节点，保存服务上线下线信息
                        zkClient.createEphemeral(serverNodePath+"/status","online");
                        System.out.println("服务器信息注册到Zookeeper成功");
                    }
                 }
            });
            System.out.println("RPC服务器启动成功，ip："+ip +",port："+port);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            this.close();
        }

    }

    /**
     * 容器销毁时关闭资源
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        System.out.println("容器销毁,关闭资源");
        this.close();
    }

    /**
     * 资源关闭
     */
    private void close(){
        zkClient.close();
        boosLoopGroup.shutdownGracefully();
        workerLoopGroup.shutdownGracefully();
    }
}
